package com.javaweb.dao.impl;

import com.javaweb.dao.ArticleDao;
import com.javaweb.model.Article;
import com.javaweb.model.Tag;
import com.javaweb.service.dto.ArticleConditionDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @desc: Article DAO Implementation
 * @author: zxzx
 * @date: 2024/10/9 9:51
 */

@Repository
public class ArticleDaoImpl implements ArticleDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Article article) {
        String sql = "INSERT INTO tb_article (user_id, title, content, status, " +
                "description, category_id, create_time, update_time)" +
                " VALUES (?,?,?,?,?,?,?,?)";
        Object[] args = new Object[]{
                article.getUserId(),
                article.getTitle(),
                article.getContent(),
                article.getStatus(),
                article.getDescription(),
                article.getCategoryId(),
                new Timestamp(article.getCreateTime().getTime()), // 使用 Timestamp 保存精确到秒的时间
                new Timestamp(article.getUpdateTime().getTime())};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int updateContent(Integer id, String newContent) {
        String sql = "UPDATE tb_article SET content = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newContent, id);
    }

    @Override
    public int updateTitle(Integer id, String newTitle) {
        String sql = "UPDATE tb_article SET title = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newTitle, id);
    }

    @Override
    public int deleteById(Integer id) {
        String sql = "DELETE FROM tb_article WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Article> selectByUserId(Integer userId) {
        String sql = "SELECT a.*, " +
                " t.id as tag_id, t.name as tag_name, t.create_time as tag_create_time, t.update_time as tag_update_time, " +
                " c.sup, c.opp " +
                " FROM tb_article a " +
                " LEFT JOIN tb_article_tag at ON a.id=at.article_id " +
                " LEFT JOIN tb_tag t ON t.id=at.tag_id " +
                " LEFT JOIN " +
                " (SELECT article_id, IFNULL(SUM(support), 0) AS sup, IFNULL(SUM(oppose),0) AS opp " +
                " FROM tb_comment GROUP BY article_id) c " +
                " ON c.article_id=a.id " +
                " WHERE a.user_id = ?";

        return jdbcTemplate.query(sql, new Object[]{userId},
                rs -> {
                    Map<Integer, Article> articleMap = new HashMap<>();
                    while (rs.next()) {
                        Integer articleId = rs.getInt("id");
                        Article article = articleMap.get(articleId);
                        if (ObjectUtils.isEmpty(article)) {
                            article = new Article();
                            article.setId(articleId);
                            article.setUserId(userId);
                            article.setTitle(rs.getString("title"));
                            article.setContent(rs.getString("content"));
                            article.setCreateTime(rs.getTimestamp("create_time")); // 使用 Timestamp 获取精确到秒的时间
                            article.setUpdateTime(rs.getTimestamp("update_time"));
                            article.setStatus(rs.getInt("status"));
                            article.setDescription(rs.getString("description"));
                            article.setCategoryId(rs.getInt("category_id"));
                            article.setTags(new ArrayList<>());
                            articleMap.put(articleId, article);
                        }

                        Integer tagId = rs.getInt("tag_id");
                        if (tagId != null) {
                            Tag tag = new Tag();
                            tag.setId(tagId);
                            tag.setName(rs.getString("tag_name"));
                            tag.setCreateTime(rs.getTimestamp("tag_create_time"));
                            tag.setUpdateTime(rs.getTimestamp("tag_update_time"));
                            article.getTags().add(tag);
                        }
                        article.setSupportCount(rs.getInt("sup"));
                        article.setOpposeCount(rs.getInt("opp"));
                    }
                    return new ArrayList<>(articleMap.values());
                });
    }

    @Override
    public int selectId(Integer userId, String title, Date createTime) {
        String sql = "SELECT id FROM tb_article WHERE user_id = ? AND title = ? AND create_time = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{userId, title, new java.sql.Date(createTime.getTime())}, Integer.class);
    }


    @Override
    public List<Article> selectByKeyword(String keyword) {
        String sql = "SELECT * FROM tb_article WHERE title LIKE ? OR content LIKE ?";
        return jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", "%" + keyword + "%"},
                new RowMapper<Article>() {
                    @Override
                    public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Article article = new Article();
                        article.setId(rs.getInt("id"));
                        article.setTitle(rs.getString("title"));
                        article.setContent(rs.getString("content"));
                        article.setStatus(rs.getInt("status"));
                        article.setDescription(rs.getString("description"));
                        article.setCategoryId(rs.getInt("category_id"));
                        article.setCreateTime(rs.getTimestamp("create_time")); // 使用 Timestamp 获取精确到秒的时间
                        article.setUpdateTime(rs.getTimestamp("update_time"));
                        return article;
                    }
                });
    }


    // 构造方法注入 JdbcTemplate


    @Override
    public List<Article> selectByTimePeriod(Date startTime, Date endTime) {
        StringBuilder sql = new StringBuilder("SELECT * FROM tb_article WHERE 1=1");

        // 动态拼接时间条件，确保精确到秒
        if (startTime != null) {
            sql.append(" AND create_time >= ?");
        }
        if (endTime != null) {
            sql.append(" AND create_time <= ?");
        }

        // 按创建时间降序排列
        sql.append(" ORDER BY create_time DESC");

        // 查询并返回结果
        Object[] params = new Object[]{
                startTime != null ? new Timestamp(startTime.getTime()) : null,
                endTime != null ? new Timestamp(endTime.getTime()) : null
        };

        List<Article> articles = jdbcTemplate.query(sql.toString(),
                params, new BeanPropertyRowMapper<>(Article.class));

        // 如果查询结果为空，返回 null
        return articles.isEmpty() ? null : articles;
    }
    @Override
    public List<Article> selectByTag(Integer tagId) {
        // SQL 查询，关联 tb_article 和 tb_article_tag 表
        String sql = "SELECT a.* FROM tb_article a " +
                "JOIN tb_article_tag at ON a.id = at.article_id " +
                "WHERE at.tag_id = ?";

        // 执行查询
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{tagId}, new BeanPropertyRowMapper<>(Article.class));

        // 如果没有结果，返回 null
        return articles.isEmpty() ? null : articles;
    }
    @Override
    public List<Article> selectByCategory(Integer categoryId) {
        String sql = "SELECT * FROM tb_article WHERE category_id = ?";
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{categoryId}, new BeanPropertyRowMapper<>(Article.class));
        return articles.isEmpty() ? null : articles;
    }



    @Override
    public int updateStatus(Integer id, Integer status) {
        String sql = "UPDATE tb_article SET status = ? WHERE id=?" ;
        return jdbcTemplate.update(sql, new Object[]{status, id});
    }

    @Override
    public Article selectById(String articleId) {
        String sql = "SELECT * FROM tb_article WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(Article.class));
    }

    @Override
    public int countByConditions(ArticleConditionDto articleCond) {
        String sql = "SELECT COUNT(*) FROM tb_article WHERE 1=1";
        List<Object> params = new ArrayList<>();

        if (articleCond.getKeyword() != null) {
            sql += " AND title LIKE ?";
            params.add("%" + articleCond.getKeyword() + "%");
        }
        if (articleCond.getStatus() != null) {
            sql += " AND status = ?";
            params.add(articleCond.getStatus());
        }
        return jdbcTemplate.queryForObject(sql, params.toArray(), Integer.class);

    }

    @Override
    public List<Article> selectByConditions(ArticleConditionDto articleCond, int fromIndex, int pageSize) {
        String sql = "SELECT * FROM tb_article WHERE 1=1";
        List<Object> params = new ArrayList<>();

        if (articleCond.getKeyword() != null) {
            sql += " AND title LIKE ?";
            params.add("%" + articleCond.getKeyword() + "%");
        }
        if (articleCond.getStatus() != null) {
            sql += " AND status = ?";
            params.add(articleCond.getStatus());
        }
        sql += " LIMIT ?, ?"; // 添加分页
        params.add(fromIndex);
        params.add(pageSize);

        return jdbcTemplate.query(sql, params.toArray(), new BeanPropertyRowMapper<>(Article.class));
    }

    @Override
    public int updatearticle(Article article) {
        String sql = "UPDATE tb_article SET title=?, content=?, description=?, category_id=?, status=? WHERE id=?";

        return jdbcTemplate.update(sql, article.getTitle(), article.getContent(),
                article.getDescription(), article.getCategoryId(), article.getStatus(), article.getId());
    }
}
